package com.wollo.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wollo.domain.AjaxResult;

import com.wollo.student.service.CheckService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author OuYang
 * @date 2024/9/1720:27
 * @description 自定义拦截器  用来拦截签到相关的请求
 */
//
@Component
public class SignInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前系统时间
        LocalTime now = LocalTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss");
        String format = df.format(now);
        LocalTime parse = LocalTime.parse(format, df);

        //校验
        int i = Integer.parseInt(request.getParameter("signStatus"));
        boolean result = false;
        switch (i) {
            case CheckService.CHECK_STATUS_MORNING:  //校验早上签到 8:00 -- 9:00之间
                result = parse.isAfter(LocalTime.parse("08:00:00", df)) && parse.isBefore(LocalTime.parse("09:00:00", df));
                break;
            case CheckService.CHECK_STATUS_MOON:  //校验中午签到: 13:00--14:00
                result = parse.isAfter(LocalTime.parse("13:00:00", df)) && parse.isBefore(LocalTime.parse("14:00:00", df));
                break;
            case CheckService.CHECK_STATUS_NIGHT: //校验晚上签到: 18:30-- 19:30
                result = parse.isAfter(LocalTime.parse("18:30:00", df)) && parse.isBefore(LocalTime.parse("19:30:00", df));
                break;
        }

        //判断
        if (!result) {//如果不在签到时间段内  则返回错误信息
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(AjaxResult.ok(330)));
        }
        return result;
    }
}
